#include "../logs/log.h"
#include <thread>
void bench(const std::string &logger_name, size_t thr_cnt, size_t msg_len, size_t msg_nums)
{
    // 获取日志器
    logs::logger::ptr lp = logs::getLogger(logger_name);
    if (lp.get() == nullptr)
        return;
    // 获取日志消息
    std::string msg(msg_len, 'k');
    // 创建指定数量线程
    std::vector<std::thread> threads;
    // 每个线程输出的数量
    size_t sz = msg_nums / thr_cnt;
    // 统计每个线程执行时间
    std::vector<double> cost_time(thr_cnt);
    for (int i = 0; i < thr_cnt; i++)
    {
        threads.emplace_back([&, i]()
                             {
            // 线程内部计时
            auto start = std::chrono::high_resolution_clock::now();
            // 循环输出
            for(int i = 0; i < sz; i++){
                lp->fatal("%s", msg.c_str());
            }
            // 结束计时
            auto end = std::chrono::high_resolution_clock::now();
            auto cost = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);

            cost_time[i] = cost.count();
            std::cout << "线程" << i << ": "  << "\t输出日志数量：" << sz << ", 耗时：" << cost.count() << "s" << std::endl; });
    }
    for (int i = 0; i < thr_cnt; i++)
    {
        threads[i].join();
    }
    // 线程并发执行，最终消耗时间最久的，才是最终的花费时间
    double max_cost = 0;
    for (auto cost : cost_time)
        max_cost = ((max_cost < cost) ? cost : max_cost);

    std::cout << "总消耗时间: " << max_cost << std::endl;
    std::cout << "平均每秒输出: " << (size_t)(msg_nums / max_cost) << "条日志" << std::endl;
    std::cout << "平均每秒输出: " << (size_t)(msg_len * msg_nums / max_cost / 1024 / 1024) << "MB" << std::endl;
}

void sync_test()
{
    std::unique_ptr<logs::LoggerBuilder> builder = std::make_unique<logs::GlobalLoggerBuild>();
    builder->BuilderLoggerType(logs::LoggerType::LOGGER_SYNC);
    builder->BuilderLoggerName("sync_logger");
    // builder->BuilderLoggerFormatter("%m%n");
    builder->buildSink<logs::FileSink>("./aa/test.log");
    // builder->BuilderEnableUnsafeAsync();
    builder->build();
    // 单线程、日志消息100字节、输出一百万次
    bench("sync_logger", 3, 100, 1000000);
}

void async_test()
{
    std::unique_ptr<logs::LoggerBuilder> builder = std::make_unique<logs::GlobalLoggerBuild>();
    builder->BuilderLoggerType(logs::LoggerType::LOGGER_ASYNC);
    builder->BuilderLoggerName("async_logger");
    // builder->BuilderLoggerFormatter("%m%n");
    builder->buildSink<logs::FileSink>("./aa/async.log");
    builder->BuilderEnableUnsafeAsync();
    builder->build();
    // 单线程、日志消息100字节、输出一百万次
    bench("async_logger", 3, 100, 1000000);
}

int main(){
    // sync_test();
    async_test();
    return 0;
}